using System;
using System.Xml.Linq;
using PowerSearch.Utils.Helpers;

namespace PowerSearch.Utils.Extensions
{
	public static class XElementExtension
	{
		public static string ReadInnerTags(this XElement parent)
		{
			var attributes = GetAttributes(parent);
			var defaultNameSpace = GetDefaultNameSpace(parent);

			var openningTag = string.Format("<{0}", parent.Name.LocalName);
			openningTag += !string.IsNullOrEmpty(attributes) ? string.Format(" {0}", attributes) : string.Empty;
			openningTag += !string.IsNullOrEmpty(defaultNameSpace) ? string.Format(" {0}", defaultNameSpace) : string.Empty;
			openningTag += ">";

			var enddingTag = string.Format("</{0}>", parent.Name.LocalName);

			return CommonHelper.HtmlDecode(parent.ToString()).Replace(openningTag, string.Empty).Replace(enddingTag, string.Empty);
		}

		private static string GetAttributes(XElement element)
		{
			if (!element.HasAttributes)
				return string.Empty;

			var value = string.Empty;

			foreach (var attribute in element.Attributes())
			{
				value += string.Format("{0}=\"{1}\"", attribute.Name, attribute.Value) + " ";
			}

			return value.Trim();
		}

		private static string GetDefaultNameSpace(XElement element)
		{
			if (string.IsNullOrEmpty(element.Name.NamespaceName))
				return string.Empty;

			return string.Format("xmlns=\"{0}\"", element.Name.NamespaceName);
		}
	}
}

